#include "tcpclient.h"

#include "jsonrpcservice.h"
#include "jsonrpcsocket.h"
#include "jsonrpcresponsehandler.h"
#include "jsonrpcnotificationhandler.h"

#include <QTcpSocket>
#include <QStringList>
#include <QDebug>
#include <QCoreApplication>

TcpClient::TcpClient()
{
}


void TcpClient::run()
{
    QTcpSocket *socket = new QTcpSocket(this);
    socket->connectToHost("127.0.0.1", 5000);
    JsonRpcSocket *jsonsocket = new JsonRpcSocket(socket, this);

    JsonRpcResponseHandler *rep;
    //rep = jsonsocket.invokeMethod("test.executeNoParams1()");


    rep = jsonsocket->invokeMethod("test.executeNoParams()");
    QObject::connect(rep, SIGNAL(onSuccess()), this, SLOT(result()));
    QObject::connect(rep, SIGNAL(onFailed()), this, SLOT(fail()));

    rep = jsonsocket->invokeMethod("test.executeOneParam(QString)", "Coucou les amis");
    //rep = jsonsocket.invokeMethod("test.executeTwoParams(QString, int)", "Coucou les amis", 12);
    //rep = jsonsocket.invokeMethod("test.executeThreeParams(QString, int, double)", "Coucou les amis", 12, 5.8);
    QStringList list;
    list << "Coucou" << "les" << "amis";
    //rep = jsonsocket.invokeMethod("test.executeListParam(QStringList)", list);

    rep = jsonsocket->invokeMethod("test.sayHello(QString)", QString::fromUtf8("Clement MICHAUD"));
    connect(rep, SIGNAL(onSuccess()), this, SLOT(getGreetings()));
    connect(rep, SIGNAL(onFailed()), this, SLOT(fail()));

    JsonRpcNotificationHandler *notif;
    notif = jsonsocket->handleNotification("notify(QString)");
    connect(notif, SIGNAL(received()), this, SLOT(notify()));

    notif = jsonsocket->handleNotification("quit()");
    connect(notif, SIGNAL(received()), this, SLOT(quit()));

    //QObject::connect(rep, SIGNAL(onSuccess()), this, SLOT(result()));

}


void TcpClient::result(){
    qDebug() << "The call has been made";
}


void TcpClient::fail(){
    JsonRpcResponseHandler *rep = static_cast<JsonRpcResponseHandler*>(sender());
    qDebug() << "The call has failed... due to error " << rep->response().errorCode() << rep->response().errorMessage();
}

void TcpClient::getGreetings(){
    JsonRpcResponseHandler *rep = static_cast<JsonRpcResponseHandler*>(sender());
    qDebug() << "The server said you " << rep->response().result().toString();
}

void TcpClient::notify(){
    JsonRpcNotificationHandler *notif = static_cast<JsonRpcNotificationHandler*>(sender());
    qDebug() << "Notification received " << notif->notification().params().at(0).toString();
}

void TcpClient::quit(){
    qDebug() << "The server asked the client to quit...";
    QCoreApplication::quit();
}
